/*
 * Tencent is pleased to support the open source community by making KuiklyUI
 * available.
 * Copyright (C) 2025 Tencent. All rights reserved.
 * Licensed under the License of KuiklyUI;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * https://github.com/Tencent-TDS/KuiklyUI/blob/main/LICENSE
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cc.openeye.video

import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import com.cc.openeye.video.VideoConst.FUNCTION_NAME
import com.cc.openeye.video.VideoConst.FUNCTION_NAME_GET_PROGRESS
import com.cc.openeye.video.VideoConst.PARAM_NAME_CURRENT_POSITION
import com.cc.openeye.video.VideoConst.PARAM_NAME_DATA
import com.cc.openeye.video.VideoConst.PARAM_NAME_DURATION
import com.tencent.kuikly.compose.extension.MakeKuiklyComposeNode
import com.tencent.kuikly.compose.ui.Modifier
import com.tencent.kuikly.core.nvi.serialization.json.JSONObject
import com.tencent.kuikly.core.views.PlayState
import com.tencent.kuikly.core.views.VideoEvent
import com.tencent.kuikly.core.views.VideoPlayControl
import com.tencent.kuikly.core.views.VideoView
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@Composable
fun Video(
    src: String,
    playControl: VideoPlayControl,
    playTimeDidChanged: ((curTime: Int, totalTime: Int) -> Unit) = { a, b -> },
    handlerFn: ((state: PlayState, extInfo: JSONObject) -> Unit) = { a, b -> },
    modifier: Modifier = Modifier,
    videoHelper: VideoHelper? = null
) {

    MakeKuiklyComposeNode(
        factory = {
            VideoView()
        },
        modifier = modifier,
        viewInit = {
            getViewAttr().run {
                playControl(VideoPlayControl.PLAY)
                src(src)
            }
        },
        viewUpdate = {
            it.getViewAttr().run {
                src(src)
                playControl(playControl)
            }
            it.getViewEvent().run {
                playTimeDidChanged(handlerFn = playTimeDidChanged)
                playStateDidChanged(handlerFn = handlerFn)
            }
            videoHelper?.initData(it.renderView, it.getViewEvent())
        }
    )
}


internal object VideoConst {
    const val FUNCTION_NAME_GET_PROGRESS = "getProgress"
    const val FUNCTION_NAME = "functionName"
    const val PARAM_NAME_DATA = "data"
    const val PARAM_NAME_DURATION = "duration"
    const val PARAM_NAME_CURRENT_POSITION = "currentPosition"

}